<template>
  <div>
    <div class="container">
      <!-- 商家管理内容展示区 -->
      <el-card style="margin-top: 1rem;">
        <!-- 用户添加 -->
        <div class="role-operate">
          <el-button size="mini" type="primary" @click="handleAdd()">添加用户</el-button>
          <el-autocomplete style="margin-left: 2rem;" v-model="state" :fetch-suggestions="querySearchAsync"
            placeholder="请输入商家名称" @select="handleSelect"></el-autocomplete>
        </div>
        <!-- 商家管理表格 -->
        <el-table :data="userData" tooltip-effect="dark" style="width: 100%;margin-top: 1rem;">
          <el-table-column type="selection" width="55" align="center"></el-table-column>
          <!-- <el-table-column prop="id" label="ID" width="50" align="center"></el-table-column> -->
          <el-table-column type="index" width="50" align="center"></el-table-column>
          <el-table-column prop="username" label="账号" width="120" align="center"></el-table-column>
          <el-table-column prop="phone" label="联系方式" width="180" align="center"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180" align="center"></el-table-column>
          <!-- <el-table-column prop="otherMessage" label="其他信息" width="180" align="center"></el-table-column> -->
          <!-- <el-table-column label="启用" width="100" align="center">
            <template slot-scope="scope">
              <el-switch ref="userStatus" @change="handleStatusChange(scope.row)" v-model="scope.row.status">
              </el-switch>
            </template>
</el-table-column> -->
          <el-table-column prop="identityname" label="身份" width="140" align="center"></el-table-column>
          <el-table-column label="操作" width="240" align="center">
            <template slot-scope="scope">
              <el-button size="mini" @click="handleUser(scope.row)">分配角色</el-button>
              <el-button size="mini" @click="handleUpdate(scope.row)" @closed="cancelAll()">编辑</el-button>
              <el-button size="mini" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination :current-page.sync="currentPage" :page-size="10" layout="total, prev, pager, next"
            :total="userData.length">
          </el-pagination>
        </el-row>
      </el-card>
      <!-- 添加编辑用户 -->
      <el-dialog @closed="cancelAll()" :title="isEdit ? '编辑用户' : '添加用户'" :visible.sync="dialogVisible" width="40%">
        <el-form :model="nullDatas" label-width="150px" size="small">
          <el-form-item label="帐号：">
            <el-input v-model="nullDatas.username" style="width: 250px" :disabled="isEdit"></el-input>
          </el-form-item>
          <el-form-item label="联系方式：">
            <el-input v-model="nullDatas.phone" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="邮箱：">
            <el-input v-model="nullDatas.email" style="width: 250px"></el-input>
          </el-form-item>
          <!-- <el-form-item label="是否启用：">
            <el-radio-group v-model="nullData.status">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item> -->
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="small">取 消</el-button>
          <el-button type="primary" @click="handleDialogConfirm($event)" size="small">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 分配角色 -->
      <el-dialog @close="cancelAllDialogVisible()" title="分配角色" :visible.sync="allocDialogVisible" width="30%">
        <template>
          <el-form :model="nullData" label-width="60px" size="small">
            <el-form-item label="帐号：">
              <el-input v-model="nullData.username" style="width: 250px" disabled></el-input>
            </el-form-item>
          </el-form>
          <el-select v-model="allRoleLists" multiple placeholder="请选择" size="small" style="width: 80%">
            <el-option v-for="item in allRoleList" :key="item" :label="item" :value="item">
            </el-option>
          </el-select>
          <span slot="footer" class="dialog-footer">
            <el-button @click="allocDialogVisible = false" size="small">取 消</el-button>
            <el-button type="primary" @click="handleAllocDialogConfirm()" size="small">确 定</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { getUserList } from '@/api'
export default {
  name: 'MyUser',
  async mounted() {
    let { data } = await getUserList()
    this.userData = data.data
  },
  data() {
    return {
      currentPage: 5,
      // 用户数据
      userData: [],
      // 存放初始的用户数据
      oldUserData: [
        {
          id: 1,
          value: '13333333333',
          phoneNumber: '13333333333',
          email: '2445264378@qq.com',
          otherMessage: '罗一一最丑',
          // 启用状态管理
          status: true,
          identity: '超级管理员',
        },
        {
          id: 2,
          value: '14444444444',
          phoneNumber: '14444444444',
          email: '1155689378@qq.com',
          otherMessage: '弘博第二丑',
          status: false,
          identity: '超级管理员',
        },
        {
          id: 3,
          value: '15555555555',
          phoneNumber: '15555555555',
          email: '2434647378@qq.com',
          otherMessage: '老王最帅',
          status: true,
          identity: '超级管理员'
        },
      ],
      isEdit: false,
      dialogVisible: false,
      // 创建一个空对象存储体用户信息
      nullData: {
        id: null,
        value: '',
        phoneNumber: '',
        email: '',
        otherMessage: '',
        status: null,
        identity: '',
      },
      //创建令一个空对象存用户信息
      nullDatas: {
      },
      allocDialogVisible: false,
      allRoleList: ['超级管理员', '管理员', '卖家'],
      allRoleLists: [],
      allocAdminId: null,
      // 搜索内容
      restaurants: [],
      state: '',
      timeout: null,
      //创建一个新数组存放搜索后的商家管理信息
      newTableData: [],
    }
  },
  methods: {
    // 启用状态的切换
    handleStatusChange(row) {
      this.$confirm('是否要修改该状态?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$message({
          type: 'success',
          message: '修改成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消修改',
        });
        row.status = !row.status
      });
    },
    // 添加用户
    handleAdd() {
      this.dialogVisible = true;
      this.isEdit = false;
    },
    // 搜索
    querySearchAsync(queryString, cb) {
      let results = queryString ? this.restaurants.filter(this.createStateFilter(queryString)) : this.restaurants;
      // console.log(cb);
      // 返回原数据
      if (!queryString) {
        this.userData = this.oldUserData
      }

      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        cb(results);
      }, 3000 * Math.random());
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(queryString) {
      console.log(queryString);
      this.$set(this.newTableData, 0, {
        id: queryString.id,
        value: queryString.value,
        phoneNumber: queryString.phoneNumber,
        email: queryString.email,
        otherMessage: queryString.otherMessage,
        status: queryString.status,
        identity: queryString.identity,
      })
      this.userData = this.newTableData
    },
    //分配角色
    handleUser(row) {
      this.allocDialogVisible = true;
      console.log(row);
      // this.allocAdminId = row.identity;
      // console.log(this.allocAdminId);
      this.allRoleLists.push(row.identity)

      this.nullDatas.value = row.value;
    },
    //分配角色确定
    handleAllocDialogConfirm() {
      for (let i = 0; i < this.userData.length; i++) {
        if (this.userData[i].value == this.nullDatas.value) {
          console.log(this.userData[i].identity);
          this.userData[i].identity = this.allRoleLists[i]
        }
      }
      // 隐藏弹窗                                                  
      this.allocDialogVisible = false;
    },
    //取消分配角色
    cancelAllDialogVisible() {
      this.allRoleLists = []
      this.allocAdminId = null
      this.nullDatas = []
    },
    // 编辑用户
    handleUpdate(row) {
      this.dialogVisible = true;
      this.isEdit = true;
      console.log(row);
      this.nullDatas = row;
    },
    //新增/编辑用户确定
    handleDialogConfirm() {
      if (this.isEdit == false) {
        // 新增
        const newArr = {
          value: this.nullData.value,
          phoneNumber: this.nullData.phoneNumber,
          email: this.nullData.email,
          otherMessage: this.nullData.otherMessage,
          status: this.nullData.status,
        }
        this.userData.push(newArr)
      } else {
        //编辑
        for (let i = 0; i < this.userData.length; i++) {
          if (this.userData[i].value == this.nullData.value) {
            const newArr1 = {
              value: this.nullData.value,
              phoneNumber: this.nullData.phoneNumber,
              email: this.nullData.email,
              otherMessage: this.nullData.otherMessage,
              status: this.nullData.status,
              identity: this.nullData.identity,
            }
            this.userData.splice(i, 1, newArr1)
          }
        }
      }
      this.dialogVisible = false;
    },
    //删除内容
    handleDelete(row) {
      for (let i = 0; i < this.userData.length; i++) {
        if (this.userData[i] == row) {
          this.userData.splice(i, 1)
        }
      }
    },
    //清空内容
    cancelAll() {
      this.nullData.id = null,
        this.nullData.value = '',
        this.nullData.phoneNumber = '',
        this.nullData.email = '',
        this.nullData.otherMessage = '',
        this.nullData.status = null,
        this.nullData.identity = ''
    }
  },
  // mounted() {
  //   this.restaurants = this.userData
  // },
}
</script>

<style lang='scss' scoped></style>